'''
This program runs with mock data which is a list of four search items: apple, orange, pear and blueberries. Among these, apple and pear is in the savedItm to indicate already selected items. 

This program will return a dictionary with item name and recommended MAXIMUM PRICE of each items. The items that has already been selected will have a recommended price of 'empty'.

'''

def recommend(budget,savedItm,data):
 recdict = {}
 totalspent = 0.00
 for key,value in savedItm.items():
  totalspent += float(value['price'])
 leftbudget = float(budget)-totalspent
 for x in data:
  recdict[x['searchterm']]=getRecPrice(x['searchterm'],x, savedItm,data,leftbudget)
 #return full dictionary {'a':"empty", 'b':"empty",'c':"17.66", 'd':"2.99", ...}
 return recdict

# x = {'searchterm':apple, 'results':{..},{..},.., 'errors':.., 'info':..}
def getRecPrice(searchterm,x,savedItm,data,leftbudget):
 if searchterm in savedItm:
  return "empty"
 else:
  meanItmPrice = getMeanItmPrice(x)
  totalMean = getTotalMean(data,savedItm)
  return "%.2f" % (float(meanItmPrice)*float(leftbudget)/float(totalMean))

def getMeanItmPrice(x):
 pricelist = []
 resultslist = x['results']
 for result in resultslist:
  pricelist.append(result['price'])
 sortedpricelist = sorted(pricelist)
 return sortedpricelist[int(len(pricelist)/2)]


def getTotalMean(data,savedItm):
 total = 0.00
 for k in data:
  if k['searchterm'] not in savedItm:
   total += float(getMeanItmPrice(k))
 return total

def getRangePercentage(x,recprice):
 pricelist = []
 resultslist = x['results']
 for result in resultslist:
  pricelist.append(result['price'])
 sortedpricelist = sorted(pricelist)
 count=0.00
 for n in sortedpricelist:
  if float(recprice)>float(n):
   count +=1.00
 return float(count)/float(len(sortedpricelist))*100.00


def budgetWarningLevel(budget,savedItm,data):
 recList = recommend(budget,savedItm,data)
 for key, value in recList.items():
  if value =="empty":
   del recList[key]

 percentageList = {}
 for key,value in recList.items():
  for x in data:
   if key==x['searchterm']:
    percentageList[key]=getRangePercentage(x,float(value))
 
 #average the percentages
 totalPercent = 0.00
 for key,value in percentageList.items():
  totalPercent += value
 avgPercent = totalPercent/len(percentageList) 
 
 if 0<=avgPercent and avgPercent<20:
  return "red"

 elif 21<=avgPercent and avgPercent<40:
  return "orange"
 
 elif 41<=avgPercent and avgPercent<60:
  return "clear"
 
 elif 61<=avgPercent and avgPercent<80:
  return "yellow"
 
 elif 81<=avgPercent and avgPercent<=100:
  return "green"

 else:
  return "error"

'''
if __name__ == "__main__":

 data = [{'searchterm':"apple", u'results':[{u'number_of_pages': 1, u'models': [], u'price':3.99}, {u'number_of_pages': 1, u'models': [], u'price':5.99},{u'number_of_pages': 1, u'models': [], u'price':5.69}], u'errors': [], u'info': {u'total_results': 19988, u'start': 0}},{'searchterm':"orange", u'results':[{u'number_of_pages': 1, u'models': [], u'price':30.99}, {u'number_of_pages': 1, u'models': [], u'price':50.99},{u'number_of_pages': 1, u'models': [], u'price':45.69}], u'errors': [], u'info': {u'total_results': 1988, u'start': 0}},{'searchterm':"pear", u'results':[{u'number_of_pages': 1, u'models': [], u'price':14.99}, {u'number_of_pages': 1, u'models': [], u'price':15.99},{u'number_of_pages': 1, u'models': [], u'price':14.69}], u'errors': [], u'info': {u'total_results': 1988, u'start': 0}},{'searchterm':"blueberries", u'results':[{u'number_of_pages': 1, u'models': [], u'price':0.99}, {u'number_of_pages': 1, u'models': [], u'price':0.19},{u'number_of_pages': 1, u'models': [], u'price':0.69}], u'errors': [], u'info': {u'total_results': 19988, u'start': 0}}]

 savedItm = {'apple':{'id':"appleid",'price':3.99},'pear':{'id':"pearid",'price':14.99}}

 budget = 100.00

 recommendList = recommend(budget,savedItm,data)
 print recommendList
 
 print budgetWarningLevel(budget,savedItm,data)
'''







